package com.foreveross.bsl.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.foreveross.bsl.auth.Auth;
import com.foreveross.bsl.auth.service.IdentityService;


/**
 * 基础控制器类，封装应用和业务通用功能，包括导航菜单，获取当前登录用户ID，当前请求是否是AJAX请求等
 *
 * @author Wangyi
 * @version v1.0
 *
 * @date 2013-7-5
 *
 */
public abstract class BaseController {
	
	public static final String PAGE_SIZE = "10";
	public static final int PAGINATION_SIZE=10;
	public static final String SEARCH_PREFIX="so_";
	public static final String SEARCH_PARAM_NAME="searchParams";
	
	@Autowired
	private Menu mainMenu;
	
	@Autowired
	private IdentityService identityService;
	
	@Autowired
	private HttpServletRequest servletRequest;
	
	@ModelAttribute()
	public void prepareCommonModel(WebRequest request, Model model){
		setCurrentMenuItem(mainMenu);
		model.addAttribute("mainMenu", mainMenu);
		model.addAttribute("ajaxRequest", AjaxUtils.isAjaxRequest(request));
		try {
			model.addAttribute("loginUser", getCurrentUser());
		} catch (Exception e) {
		}
	}
	
	private void setCurrentMenuItem(Menu mainMenu){
		for(MenuItem item : mainMenu.getMenuItems()){
			if(item.getName().equals(this.getModuleMenuName())){
				mainMenu.setCurrentMenuItem(item);
				break;
			}
		}
		if(mainMenu.getCurrentMenuItem()==null && !mainMenu.getMenuItems().isEmpty()){
			mainMenu.setCurrentMenuItem(mainMenu.getMenuItems().iterator().next());
		}
	}
	
	protected abstract String getModuleMenuName();

	public String getCurrentUserId(){
		Auth auth=this.getCurrentUser();
		String userId=auth!=null ? auth.getAccountId() : null;
		if(auth!=null && userId==null){
			throw new RuntimeException("BUG!! 能获取当前用户:"+auth+"，但其id值为null");
		}
		return userId;
	}
	
	public Auth getCurrentUser(){
		HttpSession session=servletRequest.getSession(false);
		if(session!=null){
			Object obj=identityService.validateTicket((String)session.getAttribute("sessionKey"));
			if(obj instanceof Auth){
				Auth auth=(Auth)obj;
				return auth;
			}
		}
		throw new RuntimeException("不能获取当前用户,可能没有登录系统");
	}
	
	public void rebindParametersToRedirectAttributes(RedirectAttributes redirAttrs, HttpServletRequest request){
		@SuppressWarnings("unchecked")
		Map<String, Object> params=request.getParameterMap();
		for(Map.Entry<String, Object> entry : params.entrySet()){
			redirAttrs.addAttribute(entry.getKey(), entry.getValue());
		}
	}

}
